package com.jeefw.cloud.httpws.setup.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.NotFoundException;
import javax.xml.ws.Endpoint;

import org.apache.cxf.Bus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.endpoint.ServerImpl;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.ResourceProvider;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
import org.apache.cxf.jaxrs.swagger.Swagger2Feature;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.jeefw.cloud.httpws.ws.AuthInterceptor;
import com.jeefw.cloud.httpws.ws.CtClassJaxwsApiBuilder;
import com.jeefw.cloud.httpws.ws.jaxrs.ProductServiceImpl;
import com.jeefw.cloud.httpws.ws.jaxws.NetbarServices;

import javassist.CannotCompileException;

//http://cxf.apache.org/docs/springboot.html
@Configuration
public class CxfConfig implements InitializingBean {
	
    @Autowired
    private Bus bus;
    @Autowired
    private NetbarServices netbarServices;

    
    /** 
     * JAX-WS 
	 * 
	 * // 销毁指定的Ws
	 *	ServerImpl server = endpoint.getServer(addr);
	 *	server.destroy();
	 * 
	 */
	@Bean
	public Map<String,Endpoint> endpoints( List<APIEndpoint> apiEndpoints) {
		
		Map<String, Endpoint> endpointMap = new HashMap<String, Endpoint>();
		
		for (APIEndpoint apiEndpoint : apiEndpoints) {
			// 动态创建、发布 Ws
			try {
				
				Class jaxwsApiClass = new CtClassJaxwsApiBuilder("JaxwsApi" + apiEndpoint.getName()).method("HelloWoldService2").build().toClass();
				
				EndpointImpl endpoint = new EndpointImpl(bus, BeanUtils.instantiateClass(jaxwsApiClass));
				
				//接口发布在 addr 目录下
				endpoint.publish(apiEndpoint.getAddr());
				
				endpoint.getInInterceptors().add(new UsernamePwdAuthInterceptor());

				endpointMap.put(apiEndpoint.getAddr(), endpoint);
				
			} catch (BeanInstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (CannotCompileException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		return endpointMap;
	}
	

    @Override
    public void afterPropertiesSet() throws Exception {

    	EndpointImpl endpoint = null;
		try {
			Class FirstCaseClass = new CtClassJaxwsApiBuilder("FirstCaseV").method("HelloWoldService2").build().toClass();
			
			endpoint = new EndpointImpl(bus, BeanUtils.instantiateClass(FirstCaseClass));
			endpoint.publish("/stu/info/v1");//接口发布在 /NetbarServices 目录下
		} catch (BeanInstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CannotCompileException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// 销毁指定的Ws
		//ServerImpl server = endpoint.getServer("/stu/info/v1");
		//server.destroy();
    }
    
    @Bean
    public Endpoint endpoint() {
    	
    	//list 
    	
    	
        EndpointImpl endpoint = new EndpointImpl(bus,netbarServices);
        endpoint.publish("/NetbarServices/v1");//接口发布在 /NetbarServices 目录下
        endpoint.getInInterceptors().add(new AuthInterceptor());
        return endpoint;
    }
 

	@Bean
    public Server rsServer() {
        JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
        endpoint.setBus(bus);
        endpoint.setAddress("/ws/rest");
        // Register 2 JAX-RS root resources supporting "/sayHello/{id}" and "/sayHello2/{id}" relative paths
        endpoint.setServiceBeans(Arrays.<Object>asList(new ProductServiceImpl()));
        endpoint.setFeatures(Arrays.asList(new Swagger2Feature()));
        return endpoint.create();
    }
	
    public void main2() {  
        // 添加ResourceClass  
        List<Class<?>> resourceClassList = new ArrayList<Class<?>>();  
        resourceClassList.add(ProductServiceImpl.class);  
  
        // 添加ResourceProvider  
        List<ResourceProvider> resourceProviderList = new ArrayList<ResourceProvider>();  
        
        resourceProviderList.add(new SingletonResourceProvider(new ProductServiceImpl()));  
          
        //添加provider  
        List<Object> providerList = new ArrayList<Object>();  
        providerList.add( new JacksonJsonProvider());  
          
        //发布REST任务  
        JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();  
        factory.setAddress("http://localhost:8080/ws/rest");  
        factory.setResourceClasses(resourceClassList);  
        factory.setResourceProviders(resourceProviderList);  
        factory.setProviders(providerList);  
        factory.create();  
        System.out.println("rest ws is published!!!");  
    }  
    
}